package com.ddtech.business.sys.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddtech.business.constant.DirType;
import com.ddtech.business.sys.mapper.SysToolMapper;
import com.ddtech.business.sys.model.SysTool;
import com.ddtech.business.sys.query.SysToolQuery;
import com.ddtech.business.sys.service.SysToolService;
import com.ddtech.exception.BadRequestException;
import com.ddtech.utils.FileUtil;
import com.ddtech.utils.PageUtil;
import com.ddtech.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author bin_pu
 * @since 2020-04-14
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class SysToolServiceImpl extends ServiceImpl<SysToolMapper, SysTool> implements SysToolService {

    @Resource
    private SysToolMapper sysToolMapper;

    @Value("${file.business}")
    private String businessPath;

    @Value("${file.businessMaxSize}")
    private long businessMaxSize;


    @Override
    public Object queryAll(SysToolQuery sysToolQuery) {
        IPage page = this.page(sysToolQuery.populatePage(), sysToolQuery.autoWrapper());
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object create(String type, MultipartFile multipartFile) {
        FileUtil.checkSize(businessMaxSize, multipartFile.getSize());
        File file = null;
        StringBuffer headPath = new StringBuffer(DirType.SYS_TOOL);
        headPath.append(File.separator);
        headPath.append(type);
        headPath.append(File.separator);
        try {
            //上传
            file = FileUtil.upload(multipartFile, businessPath + headPath);
            Optional.ofNullable(file).ifPresent(f -> {
                headPath.append(f.getName());
            });
            //实体信息
            SysTool sysTool = new SysTool();
            sysTool.setFileName(FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename()));
            sysTool.setType(type);
            String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
            sysTool.setFileType(suffix);
            sysTool.setFileSize(multipartFile.getSize());
            sysTool.setFilePath(headPath.toString());
            sysTool.setUpPerson(SecurityUtils.getName());
            return sysToolMapper.insert(sysTool);
        } catch (Exception e) {
            FileUtil.del(file);
            throw e;
        }
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            SysTool sysTool = this.getById(id);
            FileUtil.del(businessPath + sysTool.getFilePath());
            this.removeById(sysTool.getId());
        }
    }

    @Override
    public void downLoad(HttpServletResponse response, String id) {
        SysTool sysTool = this.getById(id);
        File file = null;
        if (sysTool != null) {
            file = new File(businessPath + sysTool.getFilePath());
        }
        if (file != null && file.exists()) {
            FileUtil.download(response, file, null);
        } else {
            throw new BadRequestException("文件不存在");
        }
    }
}
